from vtk import *

class Selector:
    def __init__(self,drawer):
        self.drawer = drawer
    # LINK BOTH VIEWS TOGETHER
        self.drawer.view.GetRepresentation(0).SetSelectionType(2)
        self.drawer.view.GetRepresentation(0).GetAnnotationLink().AddObserver("AnnotationChangedEvent", self.select)
    
    def turn_view_callback_on(self):
        if not self.drawer.view2_callback_on:
            self.drawer.view2.GetRepresentation(0).SetSelectionType(2)
            self.drawer.view2.GetRepresentation(0).GetAnnotationLink().AddObserver("AnnotationChangedEvent", self.select)
            self.drawer.view2_callback_on = True
    
    def select(self,caller,event):
        fil = vtkIdTypeArray()
        print "Searching subgraph..."
        sel = caller.GetCurrentSelection()
        node0 = sel.GetNode(1)
        
        if node0.GetFieldType() == 3:
            sl = node0.GetSelectionList()
            if sl.GetNumberOfTuples() < 1:
                print "No concept selected"
        else:
            print "No node selected"
            return False

        x = node0.GetSelectionList().GetValue(0)
        bfs = vtkBoostBreadthFirstSearch()
        bfs.AddInputConnection(self.drawer.g.GetProducerPort())
        bfs.SetOriginVertex(x)
        
        cutter = vtkSelectionSource()
        cutter.SetContentType(7)
        cutter.SetFieldType(3)
        cutter.SetArrayName("BFS")
        cutter.AddThreshold(0,100)
        cutter.Update()
        
        extract_graph = vtkExtractSelectedGraph()
        extract_graph.AddInputConnection(bfs.GetOutputPort())
        extract_graph.SetSelectionConnection(cutter.GetOutputPort())
        extract_graph.Update()
        
        
        
        #sel = cutter.GetOutput()
        #node0.SetSelectionList(cutter.GetOutput().GetNode(0).GetSelectionList())
        
        #self.updateText(x)
    # PUT ELEMENTS IN THE SELECTION
        selected_vertices = vtkIdTypeArray()
        vit = vtkVertexListIterator()
        pedy = extract_graph.GetOutput().GetVertexData().GetPedigreeIds()
        extract_graph.GetOutput().GetVertices(vit)
        while vit.HasNext():
            a = vit.Next()
            selected_vertices.InsertNextValue(pedy.GetValue(a))

        edges = vtkIdTypeArray()
        self.drawer.g.GetInducedEdges(selected_vertices,edges)
        
        sel.GetNode(0).SetSelectionList(edges)
        sel.Update()
        self.drawer.updateText(self.drawer.lattice.GetConcept(self.drawer.vertex_inv[x]))
        self.drawer.view2.AddRepresentationFromInputConnection(extract_graph.GetOutputPort())
        self.drawer.view2.SetLayoutStrategyToPassThrough()
        
        self.turn_view_callback_on()
        
        self.drawer.view2.ResetCamera()
        self.drawer.view2.Update()
        self.drawer.view2.GetRepresentation(0).Update()
        self.drawer.view2.Render()
        #self.view.GetInteractor().Start()
        print "Subgraph search ended"
        return True

